import os
from docx import Document
from docx.shared import Pt
from docx.oxml.ns import qn
from docx.enum.text import WD_ALIGN_PARAGRAPH

# 配置
SRC_DIR = 'src'
OUTPUT_DOCX = '代码导出结果.docx'
LINES_PER_PAGE = 52  # 50-55行
KEEP_PAGES = 30
CODE_EXTS = ['.js', '.vue', '.css', '.scss', '.json', '.md']

# 递归获取所有代码文件
code_files = []
for root, dirs, files in os.walk(SRC_DIR):
    for file in files:
        ext = os.path.splitext(file)[1].lower()
        if ext in CODE_EXTS:
            code_files.append(os.path.join(root, file))

# 读取所有文件内容，按文件名分隔
all_lines = []
for filepath in sorted(code_files):
    rel_path = os.path.relpath(filepath, SRC_DIR)
    all_lines.append(f'===== {rel_path} =====')
    try:
        with open(filepath, 'r', encoding='utf-8') as f:
            lines = f.read().splitlines()
    except Exception:
        with open(filepath, 'r', encoding='gbk', errors='ignore') as f:
            lines = f.read().splitlines()
    all_lines.extend(lines)
    all_lines.append('')  # 文件间空行

# 分页
pages = []
for i in range(0, len(all_lines), LINES_PER_PAGE):
    pages.append(all_lines[i:i+LINES_PER_PAGE])

# 只保留前30页和后30页
if len(pages) > 2 * KEEP_PAGES:
    pages = pages[:KEEP_PAGES] + pages[-KEEP_PAGES:]

# 生成Word文档

doc = Document()
# 设置全局字体
style = doc.styles['Normal']
style.font.name = 'Consolas'
style._element.rPr.rFonts.set(qn('w:eastAsia'), '等线')
style.font.size = Pt(10.5)

for idx, page in enumerate(pages):
    for line in page:
        if line.startswith('===== ') and line.endswith(' ====='):
            p = doc.add_paragraph()
            run = p.add_run(line)
            run.bold = True
            run.font.size = Pt(12)
            p.alignment = WD_ALIGN_PARAGRAPH.CENTER
        else:
            p = doc.add_paragraph(line)
            p.style = style
    if idx != len(pages) - 1:
        doc.add_page_break()

# 保存
print(f'总页数: {len(pages)}，每页{LINES_PER_PAGE}行')
doc.save(OUTPUT_DOCX)
print(f'导出完成: {OUTPUT_DOCX}') 